package org.example;

import bean.DB;
import bean.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/checkoutServlet")
public class checkOutServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String userIdStr = (String) session.getAttribute("userId");

        if (userIdStr == null) {
            ResponseUtils.sendResponse(response, "用户未登录，无法进行结算", "login.jsp");
            return;
        }

        int userId = Integer.parseInt(userIdStr);
        DB db = new DB();
        double totalStars = 0;
        String userAddress = "";
        double totalAmount = 0.0;

        // 1. 获取用户地址
        String getUserAddressSql = "SELECT address FROM users WHERE id = ?";
        try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(getUserAddressSql)) {
            pstmt.setInt(1, userId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                userAddress = rs.getString("address");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "获取用户地址失败", "userinfo.jsp");
            return;
        }

        // 2. 计算购物车总积分并插入订单记录
        String getCartItemsSql = "SELECT ci.product_id, ci.quantity, p.price, p.star, p.product_name " +
                "FROM userCart ci " +
                "JOIN products p ON ci.product_id = p.id " +
                "WHERE ci.user_id = ?";
        String insertOrderSql = "INSERT INTO userorders (user_id, product_id, quantity, total_price, " +
                "user_address, orders_status, product_name, totalStar) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        try (Connection conn = db.createConn();
             PreparedStatement getCartPstmt = conn.prepareStatement(getCartItemsSql);
             PreparedStatement insertOrderPstmt = conn.prepareStatement(insertOrderSql)) {
            getCartPstmt.setInt(1, userId);
            ResultSet cartItemsRs = getCartPstmt.executeQuery();

            while (cartItemsRs.next()) {
                int productId = cartItemsRs.getInt("product_id");
                int quantity = cartItemsRs.getInt("quantity");
                double price = cartItemsRs.getDouble("price");
                double star = cartItemsRs.getDouble("star");
                String productName = cartItemsRs.getString("product_name");

                double itemTotalPrice = price * quantity;
                double itemTotalStars = star * quantity;

                totalAmount += itemTotalPrice;
                totalStars += itemTotalStars;

                // 插入订单记录
                insertOrderPstmt.setInt(1, userId); // user_id
                insertOrderPstmt.setInt(2, productId); // product_id
                insertOrderPstmt.setInt(3, quantity); // quantity
                insertOrderPstmt.setDouble(4, itemTotalPrice); // total_price
                insertOrderPstmt.setString(5, userAddress); // user_address
                insertOrderPstmt.setString(6, "未发货"); // orders_status
                insertOrderPstmt.setString(7, productName); // product_name
                // 如果totalStars为0或null，则设置为0
                insertOrderPstmt.setDouble(8, itemTotalStars == 0 ? 0 : itemTotalStars); // totalStar
                insertOrderPstmt.addBatch(); // 批量插入
            }
            insertOrderPstmt.executeBatch(); // 执行批量插入
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "插入订单失败", "userinfo.jsp");
            return;
        }

        // 3. 更新用户积分
        String updateUserStarsSql = "UPDATE users SET user_star = user_star + ? WHERE id = ?";
        try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(updateUserStarsSql)) {
            pstmt.setDouble(1, totalStars);
            pstmt.setInt(2, userId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "更新用户积分失败", "userinfo.jsp");
            return;
        }

        // 4. 清空购物车
        String clearCartSql = "DELETE FROM userCart WHERE user_id = ?";
        try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(clearCartSql)) {
            pstmt.setInt(1, userId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "清空购物车失败", "userinfo.jsp");
            return;
        }

        // 5. 返回结算成功页面
        ResponseUtils.sendResponse(response, "结算成功！已生成订单、更新积分并清空购物车。", "userinfo.jsp");
    }
}
